﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace Magento.Generation
{
    class Event : Abstract
    {
        public bool readAndCreate(string dir)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement element;

            if (!Directory.Exists(dir))
            {
                this.addMessage(dir + " Directory not exist.");
                return false;
            }

            string module_name = this.getModuleName(dir);
            if (module_name == null)
                return false;

            #region events.xml

            string[] files = Directory.GetFiles(dir, "events.xml", SearchOption.AllDirectories);
            if (files.Length == 0)
            {
                this.addMessage("events.xml file not exist.");
                return false;
            }
            var event_path = files[0];
            doc.Load(event_path);
            XmlNamespaceManager nsp = new XmlNamespaceManager(doc.NameTable);
            nsp.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            
            foreach (XmlNode _node in doc.SelectNodes(@"//config/event/observer"))
            {
                element = (XmlElement)_node;
                var instanceClass = element.GetAttribute("instance").ToString();

                if (!instanceClass.StartsWith(module_name.Replace("_", @"\")))
                {
                    this.addMessage($"{instanceClass} 此类并不属于{dir} 之下");
                    return false;
                }

                var _filePath = Regex.Replace(instanceClass, "^" + module_name.Replace("_", @"\\"), dir) + ".php";
                var php = new PHP();
                php.setFullClassName(instanceClass).setUse(@"Magento\Framework\Event\ObserverInterface").setImplements("ObserverInterface");
                var method = new List<String>();
                method.Add(@"public function execute(\Magento\Framework\Event\Observer $observer) {}");
                php.setMethod(method);
                if (php.toFile(_filePath))
                {
                    this.addMessage($"{_filePath} created");
                }

            }            
            #endregion

            return true;
        }
    }
}
